package com.zprmb.udzt;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Dialog;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.zprmb.udzt.layout.AutoLayoutActivity;
import com.zprmb.udzt.util.UpdateManager;
import com.zprmb.udzt.view.LoadingDialog;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
/**
 * BaseAtivity
 * @author shenshao
 *
 */
public class BaseLogActivity extends AutoLayoutActivity {
	
	//private BbtApplication app;
	private LoadingDialog ld;
	private SharedPreferences sp;
	private String description;
	private String url;
	private String version; 
	private boolean forceUpdate;
	private Dialog dialog; 
	private TelephonyManager tm;
	private PushAgent mPushAgent;
	private TextView tv_title;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		sp = getSharedPreferences("config", MODE_PRIVATE);
				 tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
				 ScreenListener l = new ScreenListener(this);
				  mPushAgent = PushAgent.getInstance(this);
				  mPushAgent.onAppStart();
		checkUpdatePermission();
				 
		//app = ((BbtApplication) getApplication());
		//app.addActvity(this);
		//ld = new LoadingDialog(this);
		//setImmersionStatus();
	}
//	private String token;// 手机串号
private String token;// 手机串号
	SharedPreferences.Editor ed2;
	public void checkUpdatePermission() {
		if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
				) {

			requestUpdatePermission();
		} else {

			TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		 token = tm.getDeviceId();
			ed2=sp.edit();
			ed2.putString("token", token);

			ed2.commit();
			/*token2 = tm.getDeviceId();
			ed2=sp.edit();
			ed2.putString("deviceid", token2);

			ed2.commit();*/
//            UpdateManager manager = new UpdateManager(BaseActivity.this,
//                    url);
//            manager.showDownloadDialog();
		}
	}
	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		Log.d("SplashActivity", "--> onRequestPermissionsResult:permissions = " + Arrays.toString(permissions));
		Log.d("SplashActivity", "--> onRequestPermissionsResult:grantResults = " + Arrays.toString(grantResults));
		int sum = 0;
		for (int grant : grantResults) {
			sum += grant;
		}

		switch (requestCode) {
			case 1:
				if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

					TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
			 token = tm.getDeviceId();
					ed2=sp.edit();
					ed2.putString("token", token);

					ed2.commit();
					/*token2 = tm.getDeviceId();
					ed2=sp.edit();
					ed2.putString("deviceid", token2);*/

					ed2.commit();

					Log.e("退出运行", "1");
				} else {
					token = "";
					ed2=sp.edit();
//					ed2.putString("token", token);
					ed2.putString("token", token);
					ed2.commit();
					Log.e("退出运行", "2");
				}
				break;


		}
	}


	private static final int REQUEST_UPDATE = 5;

	public void requestUpdatePermission() {
		String[] permissions = new String[]{Manifest.permission.READ_PHONE_STATE};

		ActivityCompat.requestPermissions(this, permissions, 1);

	}
	private void setImmersionStatus() {
		if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
			// 透明状态栏
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			//getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
		}
	}
	public String getdeviceId(){


		String token2 = sp.getString("token", "");
		return token2;
//		return tm.getDeviceId();
		
	}
	public String getDeviceType(){
		Build build=new Build();
		return build.MODEL;
	}
	public String getChannelName(String channelKey) {
	    String result = "";
	    if ("dev".equals(channelKey)) { result = "开发版";
	    } else if ("official".equals(channelKey)) { result = "官方版";
	    } else if ("google".equals(channelKey)) { result = "谷歌版";
	    } else if ("appchina".equals(channelKey)) { result = "应用汇版";
	    } else if ("youmi".equals(channelKey)) { result = "有米版";
	    } else if ("waps".equals(channelKey)) { result = "万普版";
	    } else if ("gfan".equals(channelKey)) { result = "机锋版";
	    } else if ("91".equals(channelKey)) { result = "91版";
	    } else if ("hiapk".equals(channelKey)) { result = "安卓版";
	    } else if ("goapk".equals(channelKey)) { result = "安智版";
	    } else if ("mumayi".equals(channelKey)) { result = "木蚂蚁版";
	    } else if ("eoe".equals(channelKey)) { result = "优亿版";
	    } else if ("nduo".equals(channelKey)) { result = "N多版";
	    } else if ("feiliu".equals(channelKey)) { result = "飞流版";
	    } else if ("crossmo".equals(channelKey)) { result = "十字猫版";
	    } else if ("liantong".equals(channelKey)) { result = "联通版";
	    } else if ("huawei".equals(channelKey)) { result = "智汇云版";
	    } else if ("qq".equals(channelKey)) { result = "腾讯版";
	    } else if ("3g".equals(channelKey)) { result = "3G版";
	    } else if ("360".equals(channelKey)) { result = "360版";
	    } else if ("baidu".equals(channelKey)) { result = "百度版";
	    } else if ("sohu".equals(channelKey)) { result = "搜狐版";
	    } else if ("samsung".equals(channelKey)) { result = "三星版";
	    } else if ("coolmart".equals(channelKey)) { result = "酷派版";
	    } else if ("meizu".equals(channelKey)) { result = "魅族版";
	    } else if ("moto".equals(channelKey)) { result = "摩托版";
	    } else if ("xiaomi".equals(channelKey)) { result = "小米版";
	    } else if ("lenovo".equals(channelKey)) { result = "联想版";
	    } else if ("zhuamob".equals(channelKey)) { result = "抓猫版";
	    } else if ("iandroid".equals(channelKey)) { result = "爱卓版";
	    } else if ("imobile".equals(channelKey)) { result = "手机之家版";
	    } else if ("uc".equals(channelKey)) { result = "UC版";
	    } else { result = "山寨版";}
	    return result;
	}

	protected void onStop() {
		super.onStop();
		
	}
	
	/**
	 * 是否息屏
	 * @param c
	 * @return
	 */
	public final boolean isScreenLocked(Context c) {
        KeyguardManager mKeyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
        return !mKeyguardManager.inKeyguardRestrictedInputMode();
    }
	

	protected void onPause() {
		super.onPause();
		// TCAgent.onPause(this);
		
		MobclickAgent.onPause(this);
	}

	protected void onResume() {
		super.onResume();
		
	}

	protected void onDestroy() {
		super.onDestroy();
		// TODO
		
		//app.removeActvity(this);
	}

	public void showToast(String str) {
		Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
	}

	public void showLoding() {
		if (ld != null) {
			ld.show();
		}
	}

	public void closeLoding() {
		if (ld != null) {
			ld.close();
		}
	}

	public String getAppVersion() {
		// 获取手机的包管理者
		PackageManager pm = getPackageManager();
		try {
			PackageInfo packInfo = pm.getPackageInfo(getPackageName(), 0);
			return packInfo.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			// 不可能发生.
			return "获取版本号失败";
		}
	}

	/*
	 * public int getAppVersionCode(){ PackageManager pm = getPackageManager();
	 * try { PackageInfo packInfo = pm.getPackageInfo(getPackageName(), 0);
	 * return packInfo.versionCode; } catch (NameNotFoundException e) {
	 * e.printStackTrace(); // 不可能发生. return 5; } }
	 */

	public String getToken() {
		return sp.getString("token", "");
	}
	public String getUserId() {
		return sp.getString("userId", "");
	}
	public String getMobile() {
		return sp.getString("mobile", "");
	}
	public String getPassWord() {
		return sp.getString("password", "");
	}
	public String getdevice_token() {
		return sp.getString("device_token", "");
	}
	public int gettab() {
		return sp.getInt("tab", 0);
	}
	public SharedPreferences getShare() {
		return sp;
	}
	
	public void setTitle(String title,Activity activity){
		tv_title=(TextView)activity.findViewById(R.id.tv_title);
		tv_title.setText(title);
	}
	/**
	 * 程序是否在前台运行
	 * @return
	 */
	
	public boolean isTopActivity(String packageName) {
		ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
		if (tasksInfo.size() > 0) {
			// System.out.println("---------------包名-----------"+tasksInfo.get(0).topActivity.getPackageName());
			// 应用程序位于堆栈的顶层
			if (packageName.equals(tasksInfo.get(0).topActivity
					.getPackageName())) {
				return true;
			}
		}
		return false;
	}
	public static boolean setMiuiStatusBarDarkMode(Activity activity, boolean darkmode) {
	    Class<? extends Window> clazz = activity.getWindow().getClass();
	    try {
	        int darkModeFlag = 0;
	        Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
	        Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
	        darkModeFlag = field.getInt(layoutParams);
	        Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
	        extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
	        return true;
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return false;
	}
	public void getOutput(String str) {
		// System.out.println(str);
	}

	private void showUpVersionDialog(String content, final String url,
			final boolean forceUpdate) {
		dialog = new Dialog(BaseLogActivity.this);
		dialog.setCancelable(false);
		Window window = dialog.getWindow();
		window.setBackgroundDrawable(new ColorDrawable(getResources().getColor(
				R.color.float_transparent)));
		window.setGravity(Gravity.CENTER);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		window.setContentView(R.layout.item_splash_upversion_dialog);
		dialog.show();

		TextView tv_upversion_dialog_content = (TextView) window
				.findViewById(R.id.tv_upversion_dialog_content);
		TextView tv_upversion_dialog_clean = (TextView) window
				.findViewById(R.id.tv_upversion_dialog_clean);
		TextView tv_upversion_dialog_up = (TextView) window
				.findViewById(R.id.tv_upversion_dialog_up);
		tv_upversion_dialog_content.setText(content);
		tv_upversion_dialog_clean.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				if (dialog != null) {
					dialog.cancel();
				}
				if (forceUpdate) {
					BbtApplication.getInstance().exit();
					android.os.Process.killProcess(android.os.Process.myPid());
				} else {
					// init();
				}
			}
		});

		tv_upversion_dialog_up.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				if (dialog != null) {
					dialog.cancel();
				}
				UpdateManager manager = new UpdateManager(BaseLogActivity.this,
						url);
				manager.showDownloadDialog();
			}
		});
	}
	 public  String getMetaData(Context context) {
		 String channel = null;
			PackageManager packageManager = context.getPackageManager();
			ApplicationInfo applicationInfo;
			try {
				applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
				if (applicationInfo != null && applicationInfo.metaData != null) {
					channel =  (String) applicationInfo.metaData.get("UMENG_CHANNEL");
					channel = (String) applicationInfo.metaData.get("UMENG_CHANNEL");
				}
			} catch (NameNotFoundException e) {
				throw new RuntimeException(
						"you must set " + "" + " and " + "" + "  in your manifest file.", e);
			}

			return channel;
		}
}
